Day16 要來玩的是讓文字產生背景的陰影,並會隨著滑鼠的移動更改方向
const [offset, setOffset] = useState<Offset>({ x: 0, y: 0 });
const containerRef = useRef<HTMLDivElement | null>(null);
const handleMouseMove = (e: MouseEvent<HTMLDivElement>) => {
if (!containerRef.current) {
return;
}
const { offsetWidth: width, offsetHeight: height } = containerRef.current;
const { clientX, clientY } = e;
const { left, top } = containerRef.current.getBoundingClientRect();
const x = clientX - left;
const y = clientY - top;
const xWalk = Math.round((x / width) * 100 - 50) * 2;
const yWalk = Math.round((y / height) * 100 - 50) * 2;
setOffset({ x: xWalk, y: yWalk });
};
return (
<div
ref={containerRef}
className="flex items-center justify-center h-screen bg-gradient-to-r from-purple-500 to-pink-500"
onMouseMove={handleMouseMove}
>
<h1
className="text-6xl font-bold text-white select-none"
style={{
textShadow: `
${offset.x}px ${offset.y}px 0 rgba(255,0,255,0.7),
${offset.x * -1}px ${offset.y}px 0 rgba(0,255,255,0.7),
${offset.y}px ${offset.x * -1}px 0 rgba(0,255,0,0.7),
${offset.y * -1}px ${offset.x}px 0 rgba(0,0,255,0.7)
`,
}}
>
Mouse Move Shadow
</h1>
</div>
);